<template>
  <div ref="echartRef" style="width: 100%; height: 100%"></div>
</template>
<script setup>
import { onMounted, ref, watch } from 'vue'
import * as echarts from 'echarts/core'
import { BarChart } from 'echarts/charts'
import { TooltipComponent, TitleComponent, GridComponent } from 'echarts/components'
import { CanvasRenderer } from 'echarts/renderers'

echarts.use([TooltipComponent, TitleComponent, GridComponent, BarChart, CanvasRenderer])
const props = defineProps({
  data: {
    type: Array,
    required: true,
  },
})
// console.log('失分频次展示', props.data)
const echartRef = ref(null)
let mChart = null
onMounted(() => {
  mChart = echarts.init(echartRef.value)
  // 渲染 echarts
  renderChart()
})
const renderChart = () => {
  const data = props.data.map((item) => ({
    name: item.index_name,
    value: item.right_items,
  }))
  const option = {
    tooltip: {
      trigger: 'axis',
      formatter: function (params) {
        return `${params[0].name}: ${params[0].value}次`
      },
      backgroundColor: 'rgba(44, 23, 14, 0.80)',
      borderColor: 'rgba(44, 23, 14, 0.80)',
      textStyle: {
        color: '#fff', // 设置 tooltip 文字颜色
      },
      axisPointer: {
        // 坐标轴指示器，坐标轴触发有效
        type: 'shadow', // 默认为直线，可选为：'line' | 'shadow'
      },
    },
    grid: {
      left: '5%',
      right: '5%',
      bottom: '5%',
      top: '6%',
      containLabel: true,
    },
    xAxis: {
      type: 'category',
      data: data.map((item) => item.name),
      axisLabel: {
        interval: 0, // 强制显示所有标签
        color: '#fff',
        // fontSize: 12,
      },
      axisLine: false, // 隐藏 x 轴线
    },
    yAxis: {
      type: 'value',
      splitLine: {
        lineStyle: {
          type: 'dashed', // 设置分割线为虚线
        },
      },
      axisLabel: {
        color: '#fff', // 设置 y 轴文字颜色
      },
    },
    series: [
      {
        type: 'bar',
        data: data.map((item) => item.value),
        itemStyle: {
          color: function (params) {
            const colorList = ['#F1EEEE', '#FFA959', '#FFF67C', '#CFCFCF', '#FF5841']
            return colorList[params.dataIndex]
          },
        },
        barWidth: '30%',
        // label: {
        //   show: true,
        //   position: 'top',
        //   formatter: '{c}次',
        // },
      },
    ],
  }
  mChart.setOption(option)
}
watch(
  () => props.data,
  () => {
    renderChart()
  },
)
</script>
